//
//  IQStickerView.m
//  Created by Iftekhar Qurashi on 15/08/13.

#import "IQStickerView.h"
#import "Header.h"

#import "ARLabel.h"

#import <QuartzCore/QuartzCore.h>

CG_INLINE CGPoint CGRectGetCenter(CGRect rect)
{
    return CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
}

CG_INLINE CGPoint CGPointRorate(CGPoint point, CGPoint basePoint, CGFloat angle)
{
    CGFloat x = cos(angle) * (point.x-basePoint.x) - sin(angle) * (point.y-basePoint.y) + basePoint.x;
    CGFloat y = sin(angle) * (point.x-basePoint.x) + cos(angle) * (point.y-basePoint.y) + basePoint.y;
    
    return CGPointMake(x,y);
}

CG_INLINE CGRect CGRectSetCenter(CGRect rect, CGPoint center)
{
    return CGRectMake(center.x-CGRectGetWidth(rect)/2, center.y-CGRectGetHeight(rect)/2, CGRectGetWidth(rect), CGRectGetHeight(rect));
}

CG_INLINE CGRect CGRectScale(CGRect rect, CGFloat wScale, CGFloat hScale)
{
    return CGRectMake(rect.origin.x * wScale, rect.origin.y * hScale, rect.size.width * wScale, rect.size.height * hScale);
}

CG_INLINE CGFloat CGPointGetDistance(CGPoint point1, CGPoint point2)
{
    //Saving Variables.
    CGFloat fx = (point2.x - point1.x);
    CGFloat fy = (point2.y - point1.y);
    
    return sqrt((fx*fx + fy*fy));
}

CG_INLINE CGFloat CGAffineTransformGetAngle(CGAffineTransform t)
{
    return atan2(t.b, t.a);
}


//CG_INLINE CGSize CGAffineTransformGetScale(CGAffineTransform t)
//{
//    return CGSizeMake(sqrt(t.a * t.a + t.c * t.c), sqrt(t.b * t.b + t.d * t.d)) ;
//}


static IQStickerView *lastTouchedView;

@implementation IQStickerView
{
    CGFloat _globalInset;

    CGRect initialBounds;
    CGFloat initialDistance;

    CGPoint beginningPoint;
    CGPoint beginningCenter;

    CGPoint prevPoint;
    CGPoint touchLocation;
    
    CGFloat deltaAngle;
    
    CGAffineTransform startTransform;
    CGRect beginBounds;
    
    UILabel *textLable;
    
    ARLabel *lable;
    CGFloat fontFloat;
    
    float qipaoJiaoduFloat;
    float textWidth;
    float textHight;
    
    UIImageView *qipaoImageView;
    
    
    
}

//@synthesize contentView = _contentView;
@synthesize enableClose = _enableClose;
@synthesize enableResize = _enableResize;
@synthesize enableRotate = _enableRotate;
@synthesize delegate = _delegate;
@synthesize showContentShadow = _showContentShadow;

-(void)didMoveToSuperview
{
    [super didMoveToSuperview];

}


- (id)initWithFrame:(CGRect)frame
{
    /*(1+_globalInset*2)*/
    if (frame.size.width < (1+12*2))     frame.size.width = 25;
    if (frame.size.height < (1+12*2))   frame.size.height = 25;
 
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setUserInteractionEnabled:YES];
        _globalInset = 12;
        
        lable = [[ARLabel alloc] init];
        [lable setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
        [lable setTextAlignment:NSTextAlignmentCenter];
        
        qipaoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 16, self.bounds.size.width-32, self.bounds.size.height-32)];
        [qipaoImageView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight)];
        [self addSubview:qipaoImageView];
        [self showBoderLyayer];
    
        [self addSubview:lable];
        
        //Close button view which is in top left corner
        closeView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 32, 32)];
        closeView.image = [UIImage imageNamed:@"trash"];
        closeView.userInteractionEnabled = YES;
        [self addSubview:closeView];
        
         //Rotating view which is in bottom left corner
        rotateView = [[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width-32, self.frame.size.height-32, 32, 32)];
        [rotateView setAutoresizingMask:(UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin)];
        rotateView.image = [UIImage imageNamed:@"Shuffle"];
        rotateView.userInteractionEnabled = YES;
        [self addSubview:rotateView];
        
        //Resizing view which is in bottom right corner
        resizeView = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.bounds.size.height-_globalInset*2-5, 32, 32 )];
        [resizeView setAutoresizingMask:(UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin)];
        resizeView.backgroundColor = [UIColor clearColor];
        resizeView.userInteractionEnabled = YES;
//        resizeView.image = [UIImage imageNamed:@"resize" ];
//        [resizeView setBackgroundColor:[UIColor redColor]];
        [self addSubview:resizeView];
        
        UIPanGestureRecognizer* moveGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveGesture:)];
//        [moveGesture setMinimumPressDuration:0.02];
        [self addGestureRecognizer:moveGesture];
        
        UITapGestureRecognizer * singleTapShowHide = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contentTapped:)];
        [self addGestureRecognizer:singleTapShowHide];
        
        UITapGestureRecognizer * singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeQipaoIMage)];
        [closeView addGestureRecognizer:singleTap];
        
        UILongPressGestureRecognizer* panResizeGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(resizeTranslate:)];
        [panResizeGesture setMinimumPressDuration:0];
//        [resizeView addGestureRecognizer:panResizeGesture];
        
        UILongPressGestureRecognizer* panRotateGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(rotateViewPanGesture:)];
        [panRotateGesture setMinimumPressDuration:0];
        [rotateView addGestureRecognizer:panRotateGesture];
        
        [moveGesture requireGestureRecognizerToFail:singleTap];
        
     }
    return self;
}



//生成边线
- (void)showBoderLyayer
{
    [qipaoImageView.layer setBorderWidth:2.0f];
    [qipaoImageView.layer setShouldRasterize:YES];
    [qipaoImageView.layer setBorderColor:uicolor(255, 204, 0).CGColor];
}

- (void)hidenBoder
{
    [qipaoImageView.layer setShouldRasterize:NO];
    [qipaoImageView.layer setBorderWidth:0.0f];
    [qipaoImageView.layer setBorderColor:uicolor(255, 204, 0).CGColor];

}

-(void)contentTapped:(UITapGestureRecognizer*)tapGesture
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chuxianjianpan" object:nil];
}


//设置图片
- (void)setImage:(UIImage *)image
{
    [qipaoImageView setImage:image];
}



- (void)setRect:(CGRect)rect
{
    [lable setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
    lable.enlargedSize = CGSizeMake(200, 100);

    textWidth = rect.size.width;
}


//设置气泡文字
- (void)setTextString:(NSString *)textString
{
    [lable setText:textString];
}



//设置旋转角度
- (void)setJiaoduFloat:(float)jiaoduFloat
{
    qipaoJiaoduFloat = jiaoduFloat;
    [self setTransform:CGAffineTransformMakeRotation(jiaoduFloat)];
}


//设置文字颜色
- (void)setTextColor:(UIColor *)textColor
{
    [lable setTextColor:textColor];
}

//设置气泡透明度
- (void)setImageAlpha:(CGFloat)ImageAlpha
{
    [qipaoImageView setAlpha:ImageAlpha];
}



-(void)setEnableRotate:(BOOL)enableRotate
{
    _enableRotate = enableRotate;
    [rotateView setHidden:!_enableRotate];
    [rotateView setUserInteractionEnabled:_enableRotate];
}



//删除气泡
- (void)removeQipaoIMage
{
    [self removeFromSuperview];
}




-(void)singleTap:(UITapGestureRecognizer *)recognizer
{
    
    if([_delegate respondsToSelector:@selector(removeQipaoView)])
    {
        [_delegate removeQipaoView];
    }
}



-(void)moveGesture:(UIPanGestureRecognizer *)recognizer
{
    touchLocation = [recognizer locationInView:self.superview];
    
    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
//        [lastTouchedView hideEditingHandles];
        beginningPoint = touchLocation;
        beginningCenter = self.center;
 
        [self setCenter:CGPointMake(beginningCenter.x+(touchLocation.x-beginningPoint.x), beginningCenter.y+(touchLocation.y-beginningPoint.y))];

        beginBounds = self.bounds;
        
        
        if([_delegate respondsToSelector:@selector(stickerViewDidBeginEditing:)])
            [_delegate stickerViewDidBeginEditing:self];
    }
    else if (recognizer.state == UIGestureRecognizerStateChanged)
    {
        
        [self setCenter:CGPointMake(beginningCenter.x+(touchLocation.x-beginningPoint.x), beginningCenter.y+(touchLocation.y-beginningPoint.y))];
        
        
        
        
        if([_delegate respondsToSelector:@selector(stickerViewDidChangeEditing:)])
            [_delegate stickerViewDidChangeEditing:self];
    }
    else if (recognizer.state == UIGestureRecognizerStateEnded)
    {
        
        [self setCenter:CGPointMake(beginningCenter.x+(touchLocation.x-beginningPoint.x), beginningCenter.y+(touchLocation.y-beginningPoint.y))];
        
        
        
        [_delegate saveQipaoBounds:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, self.bounds.size.height) withJiaodu:qipaoJiaoduFloat withLableFrameX:lable.frame.origin.x withY:lable.frame.origin.y withLableW:lable.bounds.size.width withlableH:lable.bounds.size.height withContent:lable.text withAlpha:qipaoImageView.alpha withTextColor:[self changeUIColorToRGB:lable.textColor]];

        
        if([_delegate respondsToSelector:@selector(stickerViewDidEndEditing:)])
            [_delegate stickerViewDidEndEditing:self];
    }

    prevPoint = touchLocation;
    
    
#pragma mark-----
    
    
}





//颜色转字符串
- (NSString *) changeUIColorToRGB:(UIColor *)color{
    
    
    const CGFloat *cs=CGColorGetComponents(color.CGColor);
    
    
    NSString *r = [NSString stringWithFormat:@"%@",[self  ToHex:cs[0]*255]];
    NSString *g = [NSString stringWithFormat:@"%@",[self  ToHex:cs[1]*255]];
    NSString *b = [NSString stringWithFormat:@"%@",[self  ToHex:cs[2]*255]];
    return [NSString stringWithFormat:@"#%@%@%@",r,g,b];
    
    
}


//十进制转十六进制
-(NSString *)ToHex:(int)tmpid
{
    NSString *endtmp=@"";
    NSString *nLetterValue;
    NSString *nStrat;
    int ttmpig=tmpid%16;
    int tmp=tmpid/16;
    switch (ttmpig)
    {
        case 10:
            nLetterValue =@"A";break;
        case 11:
            nLetterValue =@"B";break;
        case 12:
            nLetterValue =@"C";break;
        case 13:
            nLetterValue =@"D";break;
        case 14:
            nLetterValue =@"E";break;
        case 15:
            nLetterValue =@"F";break;
        default:nLetterValue=[[NSString alloc]initWithFormat:@"%i",ttmpig];
            
    }
    switch (tmp)
    {
        case 10:
            nStrat =@"A";break;
        case 11:
            nStrat =@"B";break;
        case 12:
            nStrat =@"C";break;
        case 13:
            nStrat =@"D";break;
        case 14:
            nStrat =@"E";break;
        case 15:
            nStrat =@"F";break;
        default:nStrat=[[NSString alloc]initWithFormat:@"%i",tmp];
            
    }
    endtmp=[[NSString alloc]initWithFormat:@"%@%@",nStrat,nLetterValue];
    return endtmp;
}








-(void)resizeTranslate:(UIPanGestureRecognizer *)recognizer
{
    touchLocation = [recognizer locationInView:self.superview];
    //Reforming touch location to it's Identity transform.
    touchLocation = CGPointRorate(touchLocation, CGRectGetCenter(self.frame), -CGAffineTransformGetAngle(self.transform));
 
    if ([recognizer state]== UIGestureRecognizerStateBegan)
    {
        if([_delegate respondsToSelector:@selector(stickerViewDidBeginEditing:)])
            [_delegate stickerViewDidBeginEditing:self];
    }
    else if ([recognizer state] == UIGestureRecognizerStateChanged)
    {
        CGFloat wChange = (prevPoint.x - touchLocation.x); //Slow down increment
        CGFloat hChange = (touchLocation.y - prevPoint.y); //Slow down increment
        
        CGAffineTransform t = self.transform;
        [self setTransform:CGAffineTransformIdentity];
        
        CGRect scaleRect = CGRectMake(self.frame.origin.x, self.frame.origin.y,MAX(self.frame.size.width + (wChange*2), 1+_globalInset*2), MAX(self.frame.size.height + (hChange*2), 1+_globalInset*2));
        
        scaleRect = CGRectSetCenter(scaleRect, self.center);
        
        
        [self setFrame:scaleRect];
        
        
        
        [self setTransform:t];
        
        if([_delegate respondsToSelector:@selector(stickerViewDidChangeEditing:)])
            [_delegate stickerViewDidChangeEditing:self];
    }
    else if ([recognizer state] == UIGestureRecognizerStateEnded)
    {
        
        if([_delegate respondsToSelector:@selector(stickerViewDidEndEditing:)])
            [_delegate stickerViewDidEndEditing:self];
    }
    
    
    
    
    
    prevPoint = touchLocation;
    
    
    
}

-(void)rotateViewPanGesture:(UIPanGestureRecognizer *)recognizer
{
    touchLocation = [recognizer locationInView:self.superview];
    
    CGPoint center = CGRectGetCenter(self.frame);
    
    if ([recognizer state] == UIGestureRecognizerStateBegan)
    {
        
        
        deltaAngle = atan2(touchLocation.y-center.y, touchLocation.x-center.x)-CGAffineTransformGetAngle(self.transform);
        
        initialBounds = self.bounds;
        initialDistance = CGPointGetDistance(center, touchLocation);
       
        if([_delegate respondsToSelector:@selector(stickerViewDidBeginEditing:)])
            [_delegate stickerViewDidBeginEditing:self];
    }
    else if ([recognizer state] == UIGestureRecognizerStateChanged)
    {
        float ang = atan2(touchLocation.y-center.y, touchLocation.x-center.x);
        
        float angleDiff = deltaAngle - ang;

        [self setTransform:CGAffineTransformMakeRotation(-angleDiff)];
        [self setNeedsDisplay];
        
        
        double scale = sqrtf(CGPointGetDistance(center, touchLocation)/initialDistance);
        
        CGRect scaleRect = CGRectScale(initialBounds, scale, scale);
 
        
        if (scaleRect.size.width < 120.0)
        {
            [self setBounds:CGRectMake(scaleRect.origin.x, scaleRect.origin.y, 120, textHight)];
        }
        else
        {
            textHight = scaleRect.size.height;
            [self setBounds:scaleRect];
        }
//        NSLog(@"%f", textWidth);
        
        if([_delegate respondsToSelector:@selector(stickerViewDidChangeEditing:)])
            [_delegate stickerViewDidChangeEditing:self];
    }
    else if ([recognizer state] == UIGestureRecognizerStateEnded)
    {
        if([_delegate respondsToSelector:@selector(stickerViewDidEndEditing:)])
            [_delegate stickerViewDidEndEditing:self];
        
        
        float ang = atan2(touchLocation.y-center.y, touchLocation.x-center.x);
        
        float angleDiff = deltaAngle - ang;
        
        qipaoJiaoduFloat = -angleDiff;
        
#pragma mark-----
        //记录位置,将位置保存到数据库

        if (_delegate && [_delegate respondsToSelector:@selector(saveQipaoBounds:withJiaodu:withLableFrameX:withY:withLableW:withlableH:withContent:withAlpha:withTextColor:)])
        {
        
            [_delegate saveQipaoBounds:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, self.bounds.size.height) withJiaodu:qipaoJiaoduFloat withLableFrameX:lable.frame.origin.x withY:lable.frame.origin.y withLableW:lable.bounds.size.width withlableH:lable.bounds.size.height withContent:lable.text withAlpha:qipaoImageView.alpha withTextColor:[self changeUIColorToRGB:lable.textColor]];
            
        }

    }
    
    
}


- (void)hideBiangkuang
{
    [closeView setHidden:YES];
    [resizeView setHidden:YES];
    [rotateView setHidden:YES];
    [self hidenBoder];
    
//    [_contentView.layer setBorderWidth:0];
}


- (void)showBiankuang
{
    [closeView setHidden:NO];
    [resizeView setHidden:NO];
    [rotateView setHidden:NO];
    [self showBoderLyayer];
    
//    [self refresh];
//    [_contentView.layer setBorderWidth:1];
}



- (void)setjiaodu:(CGFloat)jiaodu rect:(CGRect)boundrect
{
    [self setBounds:boundrect];
    [self setTransform:CGAffineTransformMakeRotation(jiaodu)];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [lable resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"3333");
    return YES;
}


//裁剪图片
- (UIImage *)cropImage
{
    [self hideBiangkuang];
    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, [UIScreen mainScreen].scale);
    
    [self drawViewHierarchyInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) afterScreenUpdates:YES];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self showBiankuang];
    return image;
}






@end
